<template>
  <section>
    <el-form
      ref="formData"
      inline
      size="small"
      label-width="200px"
      :rules="rules"
      :model="formData"
    >
      <el-row>
        <el-form-item label="交易周期" prop="tpno">
          <el-select
            class="selectStyle"
            v-model="formData.tpno"
            placeholder="请选择"
            @change="selectChange"
            :disabled="action == 'trading'"
          >
            <el-option
              v-for="item in tpnoOptions"
              :key="item.tpno"
              :label="item.name"
              :value="item.tpno"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="报价类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="数量（度）" prop="quantity">
          <el-input type="text" v-model.number="formData.quantity" />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="最小交易量（度）" prop="min_txn_qty">
          <el-input type="text" v-model.number="formData.min_txn_qty" />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="价格（元）" prop="price">
          <el-input
            v-model.number="formData.price"
            @change="handleChange"
            type="number"
          />
          <!-- <el-input-number :min="0" :precision="2" :controls="false" v-model="formData.price" type="number" placeholder="请输入"> -->
          <!-- </el-input-number> -->
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="信誉要求" prop="min_credit">
          <el-input v-model.number="formData.min_credit" :min="1" :max="100" />
        </el-form-item>
      </el-row>
    </el-form>
    <el-row type="flex" justify="center" slot="footer" class="dialog-footer">
      <el-button size="small" type="primary" @click="handleClick"
        >确 定</el-button
      >
      <el-button size="small" @click="handleClose">关闭</el-button>
    </el-row>
  </section>
</template>
<script lang='ts'>
import { Vue, Component, Watch, Prop } from "vue-property-decorator";

@Component
export default class MyApplication extends Vue {
  @Prop()
  protected value!: any;
  @Prop()
  protected action!: any;

  // @Prop()
  // protected tpnoOptions!: any;
  protected formData: any = {
    type: "",
    price: 0,
    min_credit: 0,
  };
  // for diog
  protected options: any = [
    {
      value: "buy",
      label: "购电报价",
    },
    {
      value: "sale",
      label: "售电报价",
    },
  ];
  protected rules: any = {
    tpno: [
      {
        required: true,
        message: "请输入",
        trigger: "change",
      },
    ],
    type: [
      {
        required: true,
        message: "请输入",
        trigger: "change",
      },
    ],
    quantity: [
      {
        required: true,
        message: "请输入",
        trigger: "change",
      },
    ],
    min_txn_qty: [
      {
        required: true,
        message: "请输入",
        trigger: "change",
      },
    ],
    price: [
      // {
      //   required: true,
      //   message: "请输入",
      //   trigger: "change",
      // }
    ],
    min_credit: [
      // {
      //   required: true,
      //   message: "请输入",
      //   trigger: "change",
      // },
      // { min: 1, max: 100, message: "信誉值 0 ～ 100", trigger: "change" },
    ],
  };
  protected tpnoOptions: any = [];
  protected userInfor: any = null;

  protected handleChange(val: any) {
    this.formData.price = Number(val).toFixed(2);
  }

  protected created() {
    this.$nextTick(() => {
      this.userInfor = JSON.parse(localStorage.getItem("userInfo") as string);
      console.log(this.userInfor.type)
    if (this.userInfor.type == "consumer") {
      this.options = [
        {
          value: "buy",
          label: "购电报价",
        },
      ];
    } else {
      this.options = [
    {
      value: "buy",
      label: "购电报价",
    },
    {
      value: "sale",
      label: "售电报价",
    },
  ];
    }
    })
    this.$set(this.formData, "tpno", this.value);
    this.init();
    this.$nextTick(() => {
      this.$set(this.rules.min_credit, 0, {
        required: true,
        validator: this.minCreditRuler,
        trigger: "change",
      });
      this.$set(this.rules.price, 0, {
        required: true,
        validator: this.priceRuler,
        trigger: "change",
      });
    });
  }
  protected minCreditRuler: any = (rule: any, value: any, callback: any) => {
    if (value === "") {
      callback(new Error("请输入"));
    } else if (value < 0) {
      callback(new Error(`最小信誉值0`));
    } else if (value > 100) {
      callback(new Error(`最大信誉值100`));
    } else {
      callback();
    }
  };
  protected priceRuler: any = (rule: any, value: any, callback: any) => {
    if (value === "") {
      callback(new Error("请输入"));
    } else if (value <= 0) {
      callback(new Error(`价格必须大于0`));
    } else if (value > 10) {
      callback(new Error(`价格必须小于10`));
    } else {
      callback();
    }
  };

  protected async init() {
    try {
      const params: any = {
        page_no: 1,
        page_size: 1000,
        starttime: Math.floor(new Date().getTime() / 1000),
      };
      const res: any = await this.$api
        .getTradePeriodsQuery(params)
        .then((response: any) => {
          const {
            data: { trade_periods, current_tpno, next_tpno },
          } = response;
          this.value = current_tpno;
          localStorage.setItem("tpno", current_tpno);
          localStorage.setItem("nextTpno", next_tpno);
          this.tpnoOptions = trade_periods.map((item: any, idx: number) => {
            return {
              item,
              tpno: item.tpno,
              starttime: item.starttime,
              endtime: item.endtime,
              name: `${item.tpno}\xa0\xa0\xa0\xa0\xa0${Vue.prototype.$fmtDate(
                item.starttime
              )}\xa0\xa0\xa0\xa0\xa0${Vue.prototype.$fmtDate(item.endtime)}`,
            };
          });
          // this.selectChange(this.value);
          // this.$emit("TradingCycle", this.value);
        });
    } catch (error) {
      console.log(error);
    }
  }

  protected async handleClick() {
    (this.$refs.formData as any).validate(async (valid: boolean) => {
      if (valid) {
        const { ...params }: any = this.formData;
        params.price = params.price * 100;
        const res: any = await this.$api
          .creatOffers(params)
          .then((response: any) => {
            this.$message.success("发布报价成功");
            this.$emit("refresh");
          })
          .catch((e: any) => {
            this.$message.error("发布报价失败");
          });
      }
    });
  }
  protected handleClose() {
    this.formData = {};
    this.$emit("close");
  }
}
</script>

<style lang="scss" scoped>
.mr_w_10 {
  margin: 0 10px;
}
.el-form-item--small.el-form-item {
  width: 100%;
}
/deep/ .el-form-item--small .el-form-item__content {
  width: 60%;
}
.el-select {
  width: 100%;
}
// .el-input--small {
//   width: 100%;
// }
</style>


